package com.papercutting.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.papercutting.platform.entity.UserFavorite;
import com.papercutting.platform.repository.UserFavoriteRepository;
import com.papercutting.platform.service.UserFavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户收藏服务实现类
 */
@Slf4j
@Service
public class UserFavoriteServiceImpl implements UserFavoriteService {
    
    private final UserFavoriteRepository userFavoriteRepository;
    
    public UserFavoriteServiceImpl(UserFavoriteRepository userFavoriteRepository) {
        this.userFavoriteRepository = userFavoriteRepository;
    }
    
    @Override
    public UserFavorite save(UserFavorite userFavorite) {
        if (userFavorite.getId() == null) {
            userFavoriteRepository.insert(userFavorite);
        } else {
            userFavoriteRepository.updateById(userFavorite);
        }
        return userFavorite;
    }
    
    @Override
    public UserFavorite findById(Long id) {
        return userFavoriteRepository.selectById(id);
    }
    
    @Override
    public List<UserFavorite> findAll() {
        return userFavoriteRepository.selectList(null);
    }
    
    @Override
    public Page<UserFavorite> findAll(Pageable pageable) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserFavorite> page =
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                pageable.getPageNumber() + 1, pageable.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserFavorite> result =
            userFavoriteRepository.selectPage(page, null);
        return new PageImpl<>(result.getRecords(), pageable, result.getTotal());
    }
    
    @Override
    public void deleteById(Long id) {
        userFavoriteRepository.deleteById(id);
    }
    
    @Override
    public List<UserFavorite> findByUserId(Long userId) {
        QueryWrapper<UserFavorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return userFavoriteRepository.selectList(wrapper);
    }
    
    @Override
    public List<UserFavorite> findByTargetTypeAndTargetId(String targetType, Long targetId) {
        QueryWrapper<UserFavorite> wrapper = new QueryWrapper<>();
        wrapper.eq("target_type", targetType).eq("target_id", targetId);
        return userFavoriteRepository.selectList(wrapper);
    }
    
    @Override
    public UserFavorite findByUserIdAndTargetTypeAndTargetId(Long userId, String targetType, Long targetId) {
        QueryWrapper<UserFavorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
               .eq("target_type", targetType)
               .eq("target_id", targetId);
        // 注意：不需要手动添加 deleted = false 条件，因为 @TableLogic 会自动处理
        return userFavoriteRepository.selectOne(wrapper);
    }
    
    @Override
    public List<UserFavorite> findByUserIdAndTargetType(Long userId, String targetType) {
        QueryWrapper<UserFavorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("target_type", targetType);
        return userFavoriteRepository.selectList(wrapper);
    }
    
    /**
     * 查找指定用户和目标的所有记录（包括已删除的）
     * 使用自定义SQL完全绕过MyBatis Plus的逻辑删除过滤
     */
    private UserFavorite findAllRecords(Long userId, String targetType, Long targetId) {
        try {
            log.info("使用自定义SQL查找记录 - 用户ID: {}, 类型: {}, 目标ID: {}", userId, targetType, targetId);
            
            // 使用自定义的Repository方法，完全绕过@TableLogic
            UserFavorite record = userFavoriteRepository.findRecordIgnoreDeleted(userId, targetType, targetId);
            
            if (record != null) {
                log.info("找到记录: ID={}, deleted={}, create_time={}, update_time={}", 
                         record.getId(), record.getDeleted(), record.getCreateTime(), record.getUpdateTime());
            } else {
                log.info("未找到任何记录");
            }
            
            return record;
            
        } catch (Exception e) {
            log.error("查找记录时发生异常", e);
            return null;
        }
    }
    
    @Override
    public boolean toggleFavorite(Long userId, String targetType, Long targetId) {
        log.info("开始收藏切换操作 - 用户ID: {}, 类型: {}, 目标ID: {}", userId, targetType, targetId);
        
        // 查找有效的收藏记录（未被逻辑删除的）
        UserFavorite existingFavorite = findByUserIdAndTargetTypeAndTargetId(userId, targetType, targetId);
        
        if (existingFavorite != null) {
            // 如果已收藏，则取消收藏（逻辑删除）
            log.info("找到有效收藏记录，执行取消收藏操作，记录ID: {}, 当前deleted状态: {}", 
                     existingFavorite.getId(), existingFavorite.getDeleted());
            
            // 验证记录确实是有效的
            if (existingFavorite.getDeleted() != null && existingFavorite.getDeleted()) {
                log.warn("警告：查询到的记录已经是删除状态，这不应该发生！记录ID: {}", existingFavorite.getId());
            }
            
            int deleteResult = userFavoriteRepository.deleteById(existingFavorite.getId());
            log.info("删除操作结果: {} (1表示成功，0表示失败)", deleteResult);
            
            // 验证删除是否成功
            UserFavorite afterDelete = userFavoriteRepository.selectById(existingFavorite.getId());
            if (afterDelete != null) {
                log.info("删除后记录状态: ID={}, deleted={}", afterDelete.getId(), afterDelete.getDeleted());
            } else {
                log.info("删除后记录不存在（这可能是因为逻辑删除被过滤了）");
            }
            
            log.info("收藏记录已逻辑删除，返回false（未收藏状态）");
            return false;
        } else {
            log.info("未找到有效收藏记录，检查是否存在已删除记录");
            
            // 使用专门的方法查找所有记录（包括已删除的）
            UserFavorite anyRecord = findAllRecords(userId, targetType, targetId);
            log.info("查找所有记录结果: {}", anyRecord != null ? 
                     String.format("ID=%d, deleted=%s", anyRecord.getId(), anyRecord.getDeleted()) : "无记录");
            
            if (anyRecord != null && anyRecord.getDeleted()) {
                // 如果存在已删除的记录，恢复它（设置deleted=false）
                log.info("找到已删除记录，恢复收藏状态，记录ID: {}", anyRecord.getId());
                
                // 使用自定义方法恢复记录，绕过@TableLogic限制
                int restoreResult = userFavoriteRepository.restoreDeletedRecord(anyRecord.getId());
                log.info("恢复操作结果: {} (1表示成功，0表示失败)", restoreResult);
                
                if (restoreResult > 0) {
                    log.info("收藏记录已恢复，返回true（已收藏状态）");
                    return true;
                } else {
                    log.error("恢复收藏记录失败，记录ID: {}", anyRecord.getId());
                    throw new RuntimeException("恢复收藏记录失败");
                }
            } else if (anyRecord == null) {
                // 如果完全没有记录，创建新的收藏记录
                log.info("未找到任何记录，创建新的收藏记录");
                try {
                    UserFavorite userFavorite = new UserFavorite();
                    userFavorite.setUserId(userId);
                    userFavorite.setTargetType(targetType);
                    userFavorite.setTargetId(targetId);
                    userFavorite.setDeleted(false);
                    userFavoriteRepository.insert(userFavorite);
                    log.info("新收藏记录创建成功，返回true（已收藏状态）");
                    return true;
                } catch (Exception e) {
                    log.error("创建收藏记录失败", e);
                    // 如果是重复键异常，说明在并发情况下已有记录被创建
                    if (e.getMessage() != null && e.getMessage().contains("Duplicate entry")) {
                        log.warn("检测到重复键异常，可能是并发创建，重新查询状态");
                        // 重新查询有效记录
                        UserFavorite duplicateCheck = findByUserIdAndTargetTypeAndTargetId(userId, targetType, targetId);
                        boolean result = duplicateCheck != null;
                        log.info("重复键异常处理完成，最终状态: {}", result);
                        return result;
                    }
                    // 其他异常继续抛出
                    throw new RuntimeException("收藏操作失败: " + e.getMessage(), e);
                }
            } else {
                // 存在记录但未删除，这种情况不应该发生，记录错误
                log.error("发现异常状态：存在有效记录但初始查询未找到，记录ID: {}, deleted: {}", 
                         anyRecord.getId(), anyRecord.getDeleted());
                return true; // 假设已收藏
            }
        }
    }
}